package com.fanbo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

@Activate(group = {Constants.CONSUMER,Constants.PROVIDER})
public class TPMonitorFilter implements Filter {

  public static Map<String, ConcurrentHashMap<Long,Integer>> METHOD_EXECUTION_TIME = new HashMap<>();

  @Override
  public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

    long startTime = System.currentTimeMillis();
    try{
      return invoker.invoke(invocation);
    }finally {
      long endTime = System.currentTimeMillis();
      Integer executedTime = Integer.parseInt((endTime-startTime)+"");
      String methodName = invocation.getMethodName();
      long timestamp = System.currentTimeMillis();
      if(!METHOD_EXECUTION_TIME.containsKey(methodName)){
        ConcurrentHashMap<Long,Integer> timeMap = new ConcurrentHashMap<>();
        timeMap.put(timestamp,executedTime);
        METHOD_EXECUTION_TIME.put(methodName,timeMap);
      }
      METHOD_EXECUTION_TIME.get(methodName).put(timestamp,executedTime);
    }
  }
}
